<template>
    <div class="friend-list"> 
        <van-checkbox-group v-model="result"
            v-for="(item, index) in friend_list" :key="index">
            <van-index-bar>
                <van-index-anchor v-if="item.length != 1" :index="item[0]" />
                <van-cell 
                    clickable 
                    center 
                    :title="item.nickname"
                    v-for="(item, index2) in item.slice(1, item.length)" :key="index2"
                    @click="active_Checkbox(item)">
                    <template #icon>
                        <van-image round fit="cover" width="3.125rem" height="3.125rem" :src="item.headImgUrl"  />
                    </template>
                    <template #title>
                        <span class="text">{{ getDisplayName(item) }}</span>
                    </template>
                    <template #right-icon>
                        <van-checkbox :name="item" ref="checkboxes" @click="active_Checkbox(item)" />
                    </template>
                </van-cell>
            </van-index-bar>
        </van-checkbox-group>
        <!-- 好友列表为空显示 -->
        <van-empty 
            class="custom-image" 
            description="暂无好友" 
            image="imges/custom-empty-image.png"
            v-if="!friendList.length" />
    </div>
</template>

<script>
    import { mapGetters, mapState } from "vuex";

    export default {
        data() {
            return {
                result: [],         // 复选框组所用的数组
            };
        },
        computed: {
            ...mapState(["friendList"]),
            ...mapGetters(["friend_list"]),
        },
        methods: {
            active_Checkbox(item) { 
                let index = this.$refs.checkboxes.findIndex(i => i.name.phone == item.phone);
                this.$refs.checkboxes[index].toggle();
                this.$emit("emitResult", item); // 把选中的用户或者取消选中的用户传递給父组件
            },
            // 获取显示名称，优先显示备注
            getDisplayName(item) {
                const friend = this.friendList.find(f => f.friendId && f.friendId._id === item._id);
                if (friend && friend.remark && friend.remark.trim() !== '') {
                    return friend.remark;
                }
                return item.nickname;
            }
        },
    };
</script>

<style lang="less" scoped>
    .friend-list {
        .van-empty {
            margin-top: 20%;
        }
        .text {
            padding-left: 0.625rem;
        }
        .van-checkbox {
            padding-right: 0.625rem;
        }
        .van-index-bar {
            .van-index-bar__sidebar {
                position: fixed;
                top: 60%;
            }
        }
    }
</style>
